<template>
  <div class="activity-cont">
    <audio id="myAudio" class="hidden" controls loop>
      <source src="../assets/mp3/bg.mp3" type="audio/mp3">
    </audio>
    <audio id="lost" class="hidden" controls>
      <source src="../assets/mp3/lost.mp3" type="audio/mp3">
    </audio>
    <audio id="win" class="hidden" controls>
      <source src="../assets/mp3/win.mp3" type="audio/mp3">
    </audio>
    <!-- 倒计时开始活动 -->
    <div class="countdown-mask" v-show="data.countdownFlag">
      <div class="countdown-cont">
        <img class="countdown-title" src="../assets/detail/pic-countdown.png" alt="">
        <img class="countdown-num" :src="getImgUrl(`detail/icon-${data.countdownIndex}.png`)" alt="">
      </div>
    </div>

    <!-- 活动剩余时间 -->
    <div class="remainder" v-show="!data.countdownFlag">
      <div class="title_">剩余时间</div>
      <p>{{ data.remainderTime }}<span>s</span></p>
    </div>
    <div class="score">
      <div class="title_">分数</div>
      <div class="number">{{ data.score }}</div>
    </div>
    <!-- 红包雨 -->
    <div class="game-cont" v-if="!data.countdownFlag" ref="gameCont">
      <img class="envelope-item"
        @touchstart="onCatch(item)"
        :id="'item'+k"
        :src="getImgUrl(`img/item${item.bBoom?'Boom'+item.id%5:item.id%8}.png`)"
        v-for="(item,k) in data.gameList" 
        :key="item.id" 
        :style="{
          left: item.left+'px',
          top: `${item.top}px`,
          transform: `rotate(${item.rotate}deg)`
        }"/>
    </div>
    <van-overlay :show="data.bShowRule" @click="onClickRule">
      <img class="popRules" src="../assets/img/rules.png" alt="">
      <i class="popup-close" @click="data.bShowRule = false"></i>
    </van-overlay>
  </div>
</template>

<script setup lang="ts">
import { onMounted, onUnmounted, reactive } from 'vue';
import request from '../comm/request';
// import { showToast } from 'vant';
import { useRoute } from 'vue-router';
import { getImgUrl } from '../comm/utils';
const width = screen.width;
const height = screen.height;
const vmin = Math.min(width,height);
const vmax = Math.max(width,height);
const itemWidth = 0.15*vmin;
const data = reactive({
  userInfo: null,
  bShowRule: false,
  countdownFlag: false,
  countdownIndex: 0,
  remainderTime: 30,
  score: 0,
  currIndex : 1, // 红包id
  gameList: [],
})
onMounted(() => {
  data.bShowRule = true;
  getUserInfo();
  const audioElement = document.getElementById('myAudio') as HTMLAudioElement;
  audioElement.play()
})
let countdownTime = null;
let intervalUpdate = null;
let intervalRecycle = null;
let time = null;
onUnmounted(()=>{
    // 组件销毁清空定时器
    clearInterval(countdownTime)
    cancelAnimationFrame(intervalUpdate)
    clearInterval(intervalRecycle)
    clearInterval(time)
})
function getUserInfo () {
  request.get( `/user/info`, )
    .then((res: any) => {
      if (res.code === 1) {
        // 用户已登录
        data.userInfo = res.data
        data.bShowRule = true
      } else { 
        location.href = 'http://lottery.zunaer.com/lottery_web'
      }
    })
}
// 红包雨
function gameFun(){
  // 活动倒计时开始
  getActivityTime()
  // 添加红包
  countdownTime = setInterval(()=>{
    // 创建红包
    const bVertical = !!(Math.random()>0.35);
    const bUnder = !!(Math.random()>0.5);
    let left = 0,top = 0;
    let leftTo = 0,topTo = 0;
    let distanceX = 0,distanceY = 0;
    if (bVertical) {
      left = Math.random() * vmax - itemWidth/2;
      leftTo = Math.random() * vmax - itemWidth/2;
      top = bUnder? vmin: -itemWidth;
      topTo = bUnder? -itemWidth: vmin;
    } else {
      top = Math.random() * vmin - itemWidth/2;
      topTo = Math.random() * vmin - itemWidth/2;
      left = bUnder? vmax: -itemWidth;
      leftTo = bUnder? -itemWidth: vmax;
    }
    distanceX = leftTo - left;
    distanceY = topTo - top;
    let item = {
      id: data.currIndex,
      rotate: Math.floor(Math.random() * 50 - 20), // 倾斜角度
      // left:(itemWidth/2+Math.random()*(vmax-itemWidth*1.5)), // 定位
      left,top,leftTo,topTo,distanceX,distanceY,
      // scale: Math.random() * 0.65 + 0.65,
      // bottom: vmin,
      duration: Math.random()*2 +(bVertical?4:7),
      bBoom:Math.random()<0.15,
    }
    
    // 放进红包数组
    data.gameList.push(item)

    data.currIndex++
  }, 500)
  let now = Date.now()

  const animate = ()=>{
    const dt = Date.now() - now;
    now = Date.now();
    update(dt/1000)
    intervalUpdate = requestAnimationFrame(animate)
  }
  animate()
    intervalRecycle = setInterval(()=>{
      data.gameList = data.gameList.filter((e: any) => {
      return !(Math.abs(e.left -e.leftTo) < 0.1 && Math.abs(e.top -e.topTo) < 0.1);
    })
  },100)
  // data.bTips = true
}
function update(dt:number){
  for (const e of data.gameList) {
    e.top += dt / e.duration * e.distanceY;
    e.left += dt / e.duration * e.distanceX;
  }

}
const emit = defineEmits<{
  (event: 'activityEndFun', score: number): void
}>()
// 活动结束倒计时  num剩余的毫秒数
function getActivityTime(){
  data.remainderTime = 30
  time = setInterval(()=>{
    data.remainderTime--

    // 倒计时为0时，活动结束
    if(data.remainderTime === 0){
      clearInterval(countdownTime)
      cancelAnimationFrame(intervalUpdate)
      clearInterval(intervalRecycle)
      countdownTime = null
      clearInterval(time)
      time = null
      // 触发活动结束事件
      emit('activityEndFun',data.score)
    }
  }, 1000)
}
function onCatch(e:any){
  const idx = data.gameList.indexOf(e)
  if (idx >= 0) {
    data.gameList.splice(idx,1)
  }
  playSound(e.bBoom)
  data.score += e.bBoom?-1:1;
  data.score = Math.max(0,data.score)
}
function playSound(bBoom: boolean) {
  if(bBoom){
    const shortSound = document.getElementById('lost') as HTMLAudioElement;
    shortSound.play();
  }else {
    const shortSound = document.getElementById('win') as HTMLAudioElement;
    shortSound.play();
  }
}
const route = useRoute();
// // 领取奖品
// function receiveFun(item: any, event: any){
//   request.get(`act/go/${route.query.id}`,)
//     .then((res: any) => {
//       const { data, code, msg } = res
//       if (code === 1) {
//         // 用户已登录， 且中奖
//         hasPrizeFun(data, event.target, true)
//         data.gameList = data.gameList.filter((v1: any) => {
//           return v1.id !== item.id
//         })
//       } else if (code === 0){
//         // 未中奖
//         hasPrizeFun(data, event.target, false)
//         data.gameList = data.gameList.filter((v1: any) => {
//           return v1.id !== item.id
//         })
//       } else { 
//         // 其他情况，toast提示
//         showToast(msg);
//       }
//     })
// }
// 是否中奖
// function hasPrizeFun(data: any, receiveDom: any, flag: boolean){
//   receiveDom.style.animation = ''
//   const gameCont = document.getElementsByClassName('game-cont')[0]
//   const newDom = document.createElement("div")
//   if(flag){
//     newDom.className = 'receive-tips'
//     newDom.innerHTML = data.name
//   } else {
//     newDom.className = 'receive-tips not-receive-tips'
//     newDom.innerHTML = ''
//   }
//   newDom.style.top = receiveDom.offsetTop + 'px'
//   newDom.style.left = receiveDom.offsetLeft + 'px'
//   gameCont.appendChild(newDom)

//   setTimeout(()=>{
//     gameCont.removeChild(newDom)
//   }, 1000)

// }
// 倒计时逻辑
function countdownFun(){
  gameFun()  //暂时跳过倒计时
}
function onClickRule() {
    data.bShowRule = false
    if (!localStorage.getItem(`${data.userInfo.id}-${route.query.id}a`)) {
      // 倒计时
      countdownFun()
                  // 保存用户不是初次进入标识
      localStorage.setItem(`${data.userInfo.id}-${route.query.id}a`, 'true')
    } else {
      // 红包雨
      gameFun()
    }
}
</script>

<style lang="less" scoped>
.root{
  position: absolute;
  left: 0;
  top: 0;
  right: 0;
  bottom: 0;
}


.countdown-mask{
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, .6);
  z-index: 1;
  .countdown-cont{
    position: absolute;
    top: 50%;
    left: 0;
    height: calc(288px + 143px + 205px);
    transform: translateY(-50%);
    text-align: center;
    .countdown-title{
      width: 638px;
      height: 288px;
      margin-bottom: 148px;
    }
    .countdown-num{
      width: 205px;
      height: 205px;
    }
  }
}
.remainder{
  position: fixed;
  top: 20px;
  left: 0;
  width: 100vmax;
  .title_{
    font-family: SourceHanSansCN-Medium;
    font-weight: normal;
    font-stretch: normal;
    letter-spacing: 3px;
    color: rgb(214, 53, 8);
    text-align: center;
  }
  p{
    font-family: SourceHanSansCN-Heavy;
    font-weight: normal;
    font-stretch: normal;
    letter-spacing: 0px;
    color: rgb(214, 53, 8);
    text-align: center;
    span{
      font-size: 22px;
    }
  }
}
.hidden{
    display: none
  }
.popRules{
    width: auto;
    height: 100%;
  }
.game-cont{
  position: fixed;
  width: 100%;
  height: 100%;
  top:0;
  left:0;
  z-index: 2;
  .envelope-item{
    width: 15vmin;
    height: auto;
    position: absolute;
    z-index: 2;
    top: 10;
  }
}
.score{
  position: fixed;
  left: 12vmin;
  top: 10vmin;
  .title_{
    font-size: 15px;
    letter-spacing: 3px;
    color: rgb(214, 53, 8);
    text-align: center;
  }
  .number{
    font-size: 20px;
    color: rgb(214, 53, 8);
    text-align: center;
  }
}
</style>